package cc.plumgo.ss.yo.entity;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import cc.plumgo.j2me.utils.CustomEntity;
import cc.plumgo.ss.core.Constants;

public class Bullet extends CustomEntity {	
	public int type = BULLET_NONE;
	
	public static final int BULLET_NONE = 0;
	public static final int BULLET_BASEB = 1;
	public static final int BULLET_FOOTB = 2;
	public static final int BULLET_BASKETB = 3;
	public static final int BULLET_TYPE_NUM = 4;
	
	public int [] bulletNums;
	private int startX;
	public Bullet(int states) {
		totalState = states;
		try {
			sprites = new Sprite[totalState];
			Image img = null;

			for (int i = 0; i < totalState; i ++) {
				img = Image.createImage(Constants.BULLET_SPRITE_IMGS[i]);
				sprites[i] = new Sprite(img, Constants.BULLET_SPRITE_W[i], Constants.BULLET_SPRITE_H[i]);
				sprites[i].setVisible(false);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		bulletNums = new int[totalState];
		for (int i = 0; i < totalState; i++) {
			bulletNums[i] = 0;
		}
		
		//bulletNums[1] = 3;
		//bulletNums[2] = 2;
		//bulletNums[3] = 1;
	}
	public void start(int x, int y, int direct) {
		if (direct >= 0 || direct < DIR_NUM) {
			this.direct = direct;
		}
		for (int i = totalState - 1; i > 0; i--) {
			int tmp = bulletNums[i] - 1;
			if (tmp >= 0) {
				bulletNums[i]--;
				initBullet(i, x, y);
				return;
			}
		}
		initBullet(BULLET_NONE, x, y);
	}

	public void stop () {
		sprites[type].setVisible(false);
		visible = false;
	}
	
	public void logic() {
		if (!visible) {
			return;
		}
		int x = sprites[type].getRefPixelX();
		int y = sprites[type].getRefPixelY();
		switch(direct) {
		case DIR_LEFT : {
			x -= Constants.BULLET_SPEED;
			if (x < 0 || (startX - x) > Constants.BULLET_DISTANS[type]) {
				stop();
			}
			break;
		}
		case DIR_RIGHT : {
			x += Constants.BULLET_SPEED;
			if (x > Constants.SCENE_SIZ[0] || (x - startX) > Constants.BULLET_DISTANS[type] ) {
				stop();
			}
		}
		}
		
		sprites[type].setRefPixelPosition(x, y);
	}
	
	public boolean isFiring() {
		return visible;
	}
	
	private void initBullet(int type, int x, int y) {
		for (int i = 0; i < totalState; i++) {
			sprites[i].setRefPixelPosition(x, y);
			sprites[i].setVisible(false);
		}
		this.type = type;
		sprites[type].setVisible(true);
		visible = true;
		startX = sprites[type].getRefPixelX();
	}
	
	public void addBulletNums(int baseb, int footb, int basketb) {
		bulletNums[1] += baseb;
		bulletNums[2] += footb;
		bulletNums[3] += basketb;
	}
	
	public Sprite getCurrentSprite() {
		return sprites[type];
	}
	
	public int getType() {
		return type;
	}
}
